package com.crazyread.controller;

import com.crazyread.comment.lang.Result;
import com.crazyread.dao.CommentMapper;
import com.crazyread.imple.CommentServiceImpl;
import com.crazyread.model.domain.Comment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import sun.plugin.liveconnect.SecurityContextHelper;
import sun.security.acl.PrincipalImpl;

import java.security.Principal;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/comment")
@Api(value = "评论管理 controller" ,tags = {"评论管理接口统计"})
public class CommentController {
    @Autowired
    CommentServiceImpl commentService;
    @Autowired
    CommentMapper commentMapper;
    //获取某书籍下所有评论
    @GetMapping("/getCommentList/{bookId}")
    @ApiOperation(value = "获取某书籍下所有评论")
    public Result selAllComment(@PathVariable(value = "bookId")Integer bookId){
        List<Comment> commentList = commentService.selAllComment(bookId);
        return Result.succ(commentList);
    }
    //发表评论
    @PostMapping("/pushComment")
    @ApiOperation(value = "发表评论")
    public Result pushComment(@RequestParam("bookId") Integer bookId,
                              @RequestParam("content") String content){
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username =  String.valueOf(principal);
            Comment comment1  = new Comment();
            comment1.setCreated(new Date());
            comment1.setUsername(username);
            comment1.setContent(content);
            comment1.setBookId(bookId);
            try{
                commentService.pushComment(comment1);
                return Result.succ(comment1);
            }catch (Exception e){
                return Result.succ("发表失败");
            }

    }

    //删除某条评论
    @Transactional
    @PostMapping("/del/{id}")
    @ApiOperation(value = "删除某条评论")
    public Result del(@PathVariable(value = "id") Integer id){
        commentMapper.deleteCommentWithId(id);
        return Result.succ("删除成功");
   }
}
